<template>
    <div class="tables-conter-left">
        <el-table
            ref="leftTable"
            :data="filterTableData"
            row-key="tableName"
            height="calc(100vh - 190px)"
            @row-click="handleRow"
            @selection-change="handleSelectionChange"
            @row-dblclick="openDialog('edit', $event)"
            v-tableTop="currentPage"
            border
            :header-cell-style="{ 'text-align': 'center' }"
        >
            <el-table-column type="selection" :reserve-selection="true" width="50" align="center"> </el-table-column>
            <el-table-column prop="tableName" label="表名称" show-overflow-tooltip>
                <template slot="header" slot-scope="/* eslint-disable */ scope">
                    表名称
                    <el-popover placement="bottom" v-model="dataOption.search1.visible" @hide="hiddenSearch('search1')" @show="showSearch('search1')">
                        <template>
                            <input
                                class="tables-hd-filter"
                                type="text"
                                style="width: 160px; line-height: 1.8; padding: 0 5px"
                                v-model="dataOption.search1.temp"
                                @keypress.enter="dataOption.search1.visible = false"
                            />
                            <div style="margin: 8px">
                                <el-button size="mini" @click="dataOption.search1.visible = false">查询 </el-button>
                                <el-button type="primary" size="mini" @click="dataOption.search1.temp = ''">重置 </el-button>
                            </div>
                        </template>
                        <i class="el-icon-search" :class="[dataOption.search1.data.length ? 'active' : '']" slot="reference"></i>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column prop="tableComment" label="表说明" show-overflow-tooltip>
                <template slot="header" slot-scope="/* eslint-disable */ scope">
                    表名称
                    <el-popover placement="bottom" v-model="dataOption.search2.visible" @hide="hiddenSearch('search2')" @show="showSearch('search2')">
                        <template>
                            <input
                                class="tables-hd-filter"
                                type="text"
                                style="width: 160px; line-height: 1.8; padding: 0 5px"
                                v-model="dataOption.search2.temp"
                                @keypress.enter="dataOption.search2.visible = false"
                            />
                            <div style="margin: 8px">
                                <el-button size="mini" @click="dataOption.search2.visible = false">查询 </el-button>
                                <el-button type="primary" size="mini" @click="dataOption.search2.temp = ''">重置 </el-button>
                            </div>
                        </template>
                        <i class="el-icon-search" :class="[dataOption.search2.data.length ? 'active' : '']" slot="reference"></i>
                    </el-popover>
                </template>
            </el-table-column>
        </el-table>

        <risk-pagination :paging="page" @page-change="currentChange"></risk-pagination>
        <yh-dialog drag class="dialog" :title="dialogOption.title" :visible.sync="dialogOption.visible" :close-on-click-modal="false" width="520px">
            <div class="dialog-top-input">
                <div class="dialog-top-input-items">
                    <span>表名称</span>
                    <el-select
                        class="dialog-top-input-item"
                        v-model="dialogOption.data.tableName"
                        size="mini"
                        :disabled="dialogOption.command === 'edit'"
                        @change="changeDialogTableName"
                        filterable
                    >
                        <el-option v-for="item in dialogOption.selectList" :key="item.tableName" :label="item.tableName" :value="item.tableName">
                        </el-option>
                    </el-select>
                </div>
                <div class="dialog-top-input-items">
                    <span>表说明</span>
                    <el-input class="dialog-top-input-item" v-model="dialogOption.data.tableComment" size="mini" />
                </div>
            </div>

            <el-table :data="filterDialogTableData" :height="340" border>
                <el-table-column prop="columnName" label="字段名称" width="180" show-overflow-tooltip>
                    <template slot="header" slot-scope="/* eslint-disable */ scope">
                        字段名称
                        <el-popover placement="bottom" v-model="dialogOption.search1.visible" @hide="hiddenDialogSearch" @show="showDialogSearch">
                            <template>
                                <input
                                    class="tables-hd-filter"
                                    type="text"
                                    style="width: 160px; line-height: 1.8; padding: 0 5px"
                                    v-model="dialogOption.search1.temp"
                                    @keypress.enter="dialogOption.search1.visible = false"
                                />
                                <div style="margin: 8px">
                                    <el-button size="mini" @click="dialogOption.search1.visible = false">查询 </el-button>
                                    <el-button type="primary" size="mini" @click="dialogOption.search1.temp = ''">重置 </el-button>
                                </div>
                            </template>
                            <i class="el-icon-search" :class="[dialogOption.search1.data.length ? 'active' : '']" slot="reference"></i>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column label="字段说明">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.columnComment" size="mini"></el-input>
                    </template>
                </el-table-column>
            </el-table>
            <div class="dialog-top-tip">{{ showDialogTip }}</div>
            <div slot="footer">
                <el-button @click="dialogOption.visible = false">取 消</el-button>
                <el-button type="primary" @click="onsubmitDialog" v-preventReClick>确 定</el-button>
            </div>
        </yh-dialog>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { IMantenceTablesLeftDataItem, IMantenceTablesRightDataItem } from './mantence';
import { getCurrentPageData } from '@/utils/tools';
import { downLoadFile } from '@/utils/request';
import RiskPagination from '@/common/components/risk-pagination.vue';

@Component({
    name: 'MantenceTablesLeft',
    components: {
        RiskPagination,
    },
})
export default class MantenceTablesLeft extends Vue {
    // table 全部数据
    private tableData: IMantenceTablesLeftDataItem[] = [];
    // table 搜索功能参数
    private dataOption = {
        search1: {
            visible: false,
            temp: '',
            data: '',
        },
        search2: {
            visible: false,
            temp: '',
            data: '',
        },
    };

    page: any = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };
    // 选中项
    private cacheSelection: IMantenceTablesLeftDataItem[] = [];
    // 新增、编辑弹窗参数
    private dialogOption = {
        visible: false,
        title: '',
        command: '',
        data: {
            tableName: '',
            tableComment: '',
            fieldComments: [] as IMantenceTablesRightDataItem[],
        },
        selectList: [] as IMantenceTablesLeftDataItem[],
        // 表单筛选功能
        search1: {
            visible: false,
            temp: '',
            data: '',
        },
    };

    /**
     * 筛选后当前页数据
     */
    get filterTableData(): IMantenceTablesLeftDataItem[] {
        const search1 = this.dataOption.search1.data;
        const search2 = this.dataOption.search2.data;

        const filterData = getCurrentPageData(this.tableData, this.page.currentPage, 25).filter(item => {
            return (
                item.tableName.toLowerCase().indexOf(search1.toLowerCase()) > -1 &&
                item.tableComment.toLowerCase().indexOf(search2.toLowerCase()) > -1
            );
        });
        return filterData;
    }

    // 分页
    currentChange() {}

    /**
     * 筛选后所有页面数据
     */
    get filterTableDataAll(): IMantenceTablesLeftDataItem[] {
        const search1 = this.dataOption.search1.data;
        const search2 = this.dataOption.search2.data;

        const filterData = this.tableData.filter(item => {
            return (
                item.tableName.toLowerCase().indexOf(search1.toLowerCase()) > -1 &&
                item.tableComment.toLowerCase().indexOf(search2.toLowerCase()) > -1
            );
        });
        return filterData;
    }

    /**
     * 过滤弹窗的表格数据
     */
    get filterDialogTableData(): IMantenceTablesRightDataItem[] {
        return this.dialogOption.data.fieldComments.filter(item => {
            const columnName = item.columnName.toLowerCase();
            const search1 = this.dialogOption.search1.data.toLowerCase();
            return columnName.indexOf(search1) > -1;
        });
    }

    /**
     * 显示弹窗提示语
     */
    get showDialogTip(): string {
        const tip = '该表已存在记录，继续操作将会覆盖';
        const tableName = this.dialogOption.data.tableName;

        const isAdd = this.dialogOption.command === 'add';
        const isExist = this.tableData.some(item => item.tableName === tableName);
        return isAdd && isExist ? tip : '';
    }

    created() {
        this.queryData();
    }

    /**
     * 获取数据
     */
    queryData() {
        this.$axios.get('/original/table/comment').then((result: any) => {
            this.tableData = result.map(item => {
                item.tableComment = item.tableComment || '';
                item.tableName = item.tableName || '';
                item.fieldComments.forEach(item2 => {
                    item2.columnName = item2.columnName || '';
                    item2.columnComment = item2.columnComment || '';
                });
                return item;
            });
            this.page.total = this.tableData.length;
        });
    }

    /**
     * 开启关闭搜索框
     * @param type
     */
    hiddenSearch(type: string): void {
        if (type === 'search1') {
            this.dataOption.search1.data = this.dataOption.search1.temp;
        } else {
            this.dataOption.search2.data = this.dataOption.search2.temp;
        }
    }
    showSearch(type: string): void {
        if (type === 'search1') {
            this.dataOption.search1.temp = this.dataOption.search1.data;
        } else {
            this.dataOption.search2.temp = this.dataOption.search2.data;
        }
    }

    /**
     * 点击表格行，在右边表格传递数据
     */
    handleRow(row?: IMantenceTablesLeftDataItem): void {
        const fieldComments = row ? row.fieldComments : [];
        this.$emit('update-right-data', fieldComments);
    }

    /**
     * 选中项改变
     */
    handleSelectionChange(val) {
        this.cacheSelection = val;
    }

    /**
     * 删除方法
     */
    delSelections() {
        if (!this.cacheSelection.length) {
            this.yh_message_warn('请选择需要删除的记录');
            return;
        }
        let data = [];
        this.cacheSelection.forEach(item => {
            data.push(item.tableName);
        });

        this.$confirm(data.join(', '), '确认以下删除维护记录吗？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }).then(_ => {
            this.$axios.post('/original/delete/tab/col', data).then(result => {
                // 重新获取数据，清空右边数据和选中项
                this.cleanData(true);
            });
        });
    }

    /**
     * 导出表格
     */
    exportExcel(): void {
        let data: IMantenceTablesLeftDataItem[] = [];
        if (this.cacheSelection.length) {
            data = this.cacheSelection;
        } else if (this.filterTableDataAll.length) {
            data = this.filterTableDataAll;
        } else {
            this.yh_message_warn('无数据！');
            return;
        }

        downLoadFile({
            url: '/original/export/tab/col/excel',
            method: 'post',
            data,
        });
    }

    /**
     * 重新获取数据，清空选中项和右边数据
     * @param backFirstPage 是否回到第一页
     */
    cleanData(backFirstPage?: boolean): void {
        this.queryData();
        this.handleRow();
        (this.$refs.leftTable as { clearSelection?: any }).clearSelection();
        if (backFirstPage) {
            this.page.currentPage = 1;
        }
    }

    /**
     * 添加、修改记录
     * @param command add：添加  edit：修改
     * @param row     需要修改的记录（只有修改时传入）
     */
    openDialog(command: string, row?: IMantenceTablesLeftDataItem): void {
        const tempData = row
            ? JSON.parse(JSON.stringify(row))
            : {
                  tableName: '',
                  tableComment: '',
                  fieldComments: [] as IMantenceTablesRightDataItem[],
              };
        if (command === 'add') {
            this.dialogOption = {
                visible: true,
                title: '新增维护记录',
                command: 'add',
                data: tempData,
                selectList: [],
                search1: {
                    visible: false,
                    temp: '',
                    data: '',
                },
            };
        } else if (command === 'edit') {
            this.dialogOption = {
                visible: true,
                title: '修改记录',
                command: 'edit',
                data: tempData,
                selectList: [],
                search1: {
                    visible: false,
                    temp: '',
                    data: '',
                },
            };
        }
        // 获取下拉列表
        this.queryDropDownList(tempData.tableName);
    }

    /**
     * 获取下拉菜单
     * 不带参数：获取所有下拉菜单 （新增）
     * 带参数  ：获取当前表下拉菜单 （编辑）
     * @param tableName
     */
    queryDropDownList(tableName?: string) {
        const temp = tableName ? '/' + tableName : '';
        this.$axios.get('/original/usertab/column' + temp).then((result: any) => {
            // // 整理数据格式
            // const data = JSON.parse(result).map(item => {
            //     let tempItem = {
            //         tableName: item.tableName,
            //         tableComment: '',
            //         fieldComments: item.columnNames.map(fItem => {
            //             return {
            //                 columnName: fItem,
            //                 columnComment: '',
            //             };
            //         }),
            //     };
            //     return item;
            // });
            // this.dialogOption.selectList = data;
            this.dialogOption.selectList = JSON.parse(result);
        });
    }

    /**
     * 添加时下拉框改变
     * @param tableName 表名
     */
    changeDialogTableName(tableName) {
        let selectList = JSON.parse(JSON.stringify(this.dialogOption.selectList));

        let data = selectList.find(item => {
            return item.tableName === tableName;
        });

        const fieldComments = data.columnNames.map(item => {
            return {
                columnName: item,
                columnComment: '',
            };
        });

        this.dialogOption.data = {
            tableName: data.tableName,
            tableComment: '',
            fieldComments: fieldComments,
        };
    }

    /**
     * 弹窗中的搜索功能
     * @param type
     */
    hiddenDialogSearch(type?: string) {
        this.dialogOption.search1.data = this.dialogOption.search1.temp;
    }
    showDialogSearch(type?: string) {
        this.dialogOption.search1.temp = this.dialogOption.search1.data;
    }

    /**
     * 提交添加、修改弹窗数据
     */
    onsubmitDialog(): void {
        const isAdd = this.dialogOption.command === 'add';
        const data = this.dialogOption.data;
        if (isAdd) {
            this.insertDialogData(data);
        } else {
            this.updateDialogData(data);
        }
    }
    insertDialogData(data: any): void {
        this.$axios.post('/original/insert/tab/col', data).then((result: any) => {
            this.cleanData();
            this.initDialog();
        });
    }
    updateDialogData(data: any): void {
        this.$axios.post('/original/update/tab/col', data).then((result: any) => {
            this.cleanData();
            this.initDialog();
        });
    }

    /**
     * 初始化弹窗
     */
    initDialog(): void {
        this.dialogOption = {
            visible: false,
            title: '',
            command: '',
            data: {
                tableName: '',
                tableComment: '',
                fieldComments: [] as IMantenceTablesRightDataItem[],
            },
            selectList: [],
            search1: {
                visible: false,
                temp: '',
                data: '',
            },
        };
    }
}
</script>

<style lang="scss" scoped>
.tables-conter-left {
    width: 50%;
    height: 100%;
    border-right: 1px solid #eee;

    .el-icon-search {
        float: right;
        line-height: 20px;
        cursor: pointer;

        &.active {
            color: #66b1ff;
            font-weight: bold;
        }
    }

    .tables-conter-left-icon {
        position: relative;

        .tables-popover {
            position: absolute;
            top: 100px;
            left: 0;
            width: 150px;
            height: 75px;
            z-index: 100;
            background-color: slategrey;
        }
    }

    .dialog {
        & /deep/ .el-dialog {
            height: 520px;

            .el-dialog__body {
                max-height: 520px;
            }
        }

        .dialog-top-input {
            display: flex;

            .dialog-top-input-items {
                width: 50%;
                display: flex;
                white-space: nowrap;
                align-items: center;

                .dialog-top-input-item {
                    margin: 3px 8px;
                }
            }
        }

        .dialog-top-tip {
            position: absolute;
            bottom: 3px;
            left: 16px;
            color: red;
            pointer-events: none;
        }
    }
}
</style>
